package com.bwsoft.admin.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.bwsoft.admin.domain.Account;
import com.bwsoft.admin.domain.Advertisement;
import com.bwsoft.admin.domain.QualityControlJoiner;
import com.bwsoft.admin.domain.valueObject.AccountVO;
import com.bwsoft.admin.service.ComAndLadService;
import com.bwsoft.api.util.Constant;
import com.bwsoft.model.Message;
import com.bwsoft.service.DictionaryDataService;
import com.bwsoft.util.MD5Util;
import com.bwsoft.util.UploadFileUtil;

@Service(ComAndLadService.NAME)
public class ComAndLadServiceImpl extends BaseServiceImpl_ybd implements ComAndLadService {

	private static Logger LOG = Logger.getLogger(ComAndLadService.class.getClass());
	@Resource(name =  DictionaryDataService.NAME)
	DictionaryDataService dictionaryDataService;

	@Override
	public List<Account> findData(Integer page, Integer rows,
			String s_accountId, String s_compName, String s_account,
			String s_attestStatus, String s_jinyongFlag, String s_accountType) {
		StringBuffer clHql = new StringBuffer();
		Map<String, String> typeMap=dictionaryDataService.getDicDataByName("account_type");
		Map<String, String> natureMap=dictionaryDataService.getDicDataByName("comp_nature");
		clHql.append("from Account as act where 1=1");
		if(s_accountId != null && !"".equals(s_accountId.trim())){
			clHql.append(" and act.accountId like '%"+s_accountId.trim()+"%'");
		}
		if(s_compName != null && !"".equals(s_compName.trim())){
			clHql.append(" and act.compName like '%"+s_compName.trim()+"%'");
		}
		if(s_account != null && !"".equals(s_account.trim())){
			clHql.append(" and act.account like '%"+s_account.trim()+"%'");
		}
		if(s_attestStatus != null && !"".equals(s_attestStatus.trim())){
			if("0".equals(s_attestStatus.trim())){
				clHql.append(" and (act.attestStatus != '1' or act.attestStatus is null) ");
			}else
				clHql.append(" and act.attestStatus = '"+s_attestStatus.trim()+"'");
		}
		if(s_jinyongFlag != null && !"".equals(s_jinyongFlag.trim())){
			if("0".equals(s_jinyongFlag.trim())){
				clHql.append(" and (act.jinyongFlag != '1' or act.jinyongFlag is null) ");
			}else
				clHql.append(" and act.jinyongFlag = '"+s_jinyongFlag.trim()+"'");
		}
		if(s_accountType != null && !"".equals(s_accountType.trim())){
			clHql.append(" and act.accountType = '"+s_accountType.trim()+"'");
		}
		clHql.append(" and act.accountType in (1,2)");
		clHql.append(" order by act.addTime desc");
		List<Account> actData = accountDao.findPage(clHql.toString(), rows, (page - 1) * rows);
		for (Account act : actData) {
			if(act.getAccountType()!=null)
				act.setAccountTypeName(typeMap.containsKey(act.getAccountType().toString())?typeMap.get(act.getAccountType().toString()):"" );
			if(act.getCompNature()!=null)
				act.setCompNatureName(natureMap.containsKey(act.getCompNature().toString())?natureMap.get(act.getCompNature().toString()):"" );
//			act.setAttestStatusName(dictionaryDataService.getDicValueDataByNameValue("attest_Status", act.getAttestStatus()));
			act.setCompNature(null);
			if(act.getAccountType() == 2){
//				借用compNature 里面是研究所下的检验人员个数
				act.setCompNature(accountDao.findByHql("from Account where company ="+act.getAccountId()).size());
			}
		}
		return actData;
	}

	@Override
	public Long getTotalCount(String s_accountId, String s_compName, String s_account,
			String s_attestStatus, String s_jinyongFlag, String s_accountType) {
		StringBuffer clHql = new StringBuffer();
		clHql.append("select count(*) from Account as act where 1=1");
		if(s_accountId != null && !"".equals(s_accountId.trim())){
			clHql.append(" and act.accountId like '%"+s_accountId.trim()+"%'");
		}
		if(s_compName != null && !"".equals(s_compName.trim())){
			clHql.append(" and act.compName like '%"+s_compName.trim()+"%'");
		}
		if(s_account != null && !"".equals(s_account.trim())){
			clHql.append(" and act.account like '%"+s_account.trim()+"%'");
		}
		if(s_attestStatus != null && !"".equals(s_attestStatus.trim())){
			if("0".equals(s_attestStatus.trim())){
				clHql.append(" and (act.attestStatus != '1' or act.attestStatus is null) ");
			}else
				clHql.append(" and act.attestStatus = '"+s_attestStatus.trim()+"'");
		}
		if(s_jinyongFlag != null && !"".equals(s_jinyongFlag.trim())){
			if("0".equals(s_jinyongFlag.trim())){
				clHql.append(" and (act.jinyongFlag != '1' or act.jinyongFlag is null) ");
			}else
				clHql.append(" and act.jinyongFlag = '"+s_jinyongFlag.trim()+"'");
		}
		if(s_accountType != null && !"".equals(s_accountType.trim())){
			clHql.append(" and act.accountType = '"+s_accountType.trim()+"'");
		}
		clHql.append(" and act.accountType in (1,2)");
		Long count;
		count = (Long)accountDao.findByHql(clHql.toString()).get(0);
		return count;
	}

	@Override
	public Message saveOrUpdateInfo(Account cl, File clImg1, String clImg1FileName, File clImg2, String clImg2FileName, String cnasFlag) {
		Message msg = new Message();
		com.bwsoft.admin.domain.File filePojo = new com.bwsoft.admin.domain.File();
		try {
			if(cl.getAccountId() != null && !"".equals(cl.getAccountId())){
				Account updataBefor = accountDao.findById(cl.getAccountId());
//				cl.setAddTime(updataBefor.getAddTime());
//				cl.setHeadImgURL(updataBefor.getHeadImgURL());
//				cl.setImg1(updataBefor.getImg1());
//				cl.setImg2(updataBefor.getImg2());
				if(cl.getCompName().trim() != null || !"".equals(cl.getCompName().trim())){
					updataBefor.setCompName(cl.getCompName().trim());
				}
				if(cl.getCompNature() != null || !"".equals(cl.getCompNature())){
					updataBefor.setCompNature(cl.getCompNature());
				}
				if(cl.getEmail().trim() != null || !"".equals(cl.getEmail().trim())){
					updataBefor.setEmail(cl.getEmail().trim());
				}
				if(cl.getFax().trim() != null || !"".equals(cl.getFax().trim())){
					updataBefor.setFax(cl.getFax().trim());
				}
				if(cl.getLinkMan().trim() != null || !"".equals(cl.getLinkMan().trim())){
					updataBefor.setLinkMan(cl.getLinkMan().trim());
				}
				if(cl.getPhone().trim() != null || !"".equals(cl.getPhone().trim())){
					updataBefor.setPhone(cl.getPhone().trim());
				}
				if(cnasFlag != null || !"".equals(cnasFlag)){
					if("1".equals(cnasFlag))
						updataBefor.setCnasFlag(true);
					else
						updataBefor.setCnasFlag(false);
				}
				cl = updataBefor;
			}
			//---------附件上传（如果没上传则取原数据库内容保存）--------------
			if(clImg1 != null && !"".equals(clImg1)){
				Calendar now = Calendar.getInstance();
				String annexFilepath0 = ServletActionContext.getServletContext().getRealPath(Constant.PATH_IMG_SHANGCHUAN+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1));
				String annexFileName0 = null ;
				annexFileName0=UUID.randomUUID().toString()+clImg1FileName.substring(clImg1FileName.lastIndexOf('.'), clImg1FileName.length());
				UploadFileUtil.uploadOneFile(annexFileName0, clImg1, annexFilepath0);
				cl.setImg1(Constant.PATH_IMG_SHANGCHUAN+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+annexFileName0);
			}
			if(clImg2 != null && !"".equals(clImg2)){
				Calendar now = Calendar.getInstance();
				String annexFilepath1 = ServletActionContext.getServletContext().getRealPath(Constant.PATH_IMG_SHANGCHUAN+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1));
				String annexFileName1 = null ;
				annexFileName1=UUID.randomUUID().toString()+clImg2FileName.substring(clImg2FileName.lastIndexOf('.'), clImg2FileName.length());
				UploadFileUtil.uploadOneFile(annexFileName1, clImg2, annexFilepath1);
				cl.setImg2(Constant.PATH_IMG_SHANGCHUAN+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+annexFileName1);
			}
			accountDao.saveOrUpdate(cl);
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message saveOrUpdatePass(Account cl) {
		Message msg = new Message();
		try {
			StringBuffer adHql = new StringBuffer();
			adHql.append("update Account cl set cl.password='"+MD5Util.md5_16(cl.getPassword()) +"' where cl.accountId = "+cl.getAccountId()); 
			accountDao.executeByHql(adHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Account comAndLadModifyInfo(Integer id) {
		Account comAndLad=null;
		try{
			comAndLad = accountDao.findById(id);
//			comAndLad.setPlaceName(dictionaryDataService.getDicValueDataByNameValue("web_advertisement", advertisement.getPlace()));
		}catch (Exception e) {
			e.printStackTrace();
		}
		return comAndLad;
	}

	@Override
	public Message certified(Integer ids) {
		Message msg = new Message();
		try {
			StringBuffer adHql = new StringBuffer();
			adHql.append("update Account cl set cl.attestStatus=1 where cl.accountId ="+ids); 
			accountDao.executeByHql(adHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message NonCertified(Integer ids) {
		Message msg = new Message();
		try {
			StringBuffer adHql = new StringBuffer();
			adHql.append("update Account cl set cl.attestStatus=0 where cl.accountId ="+ids); 
			accountDao.executeByHql(adHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message operation(Integer ids) {
		Message msg = new Message();
		try {
			StringBuffer adHql = new StringBuffer();
			adHql.append("update Account cl set cl.jinyongFlag=0 where cl.accountId ="+ids); 
			accountDao.executeByHql(adHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message forbid(Integer ids) {
		Message msg = new Message();
		try {
			StringBuffer adHql = new StringBuffer();
			adHql.append("update Account cl set cl.jinyongFlag=1 where cl.accountId ="+ids); 
			accountDao.executeByHql(adHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}
	
	@Override
	public List<Account> findInspectorsData(Integer page, Integer rows, int qcId) {
		StringBuffer inspectorsHql = new StringBuffer();
		inspectorsHql.append("from Account as inspectors where 1=1");
		inspectorsHql.append("and inspectors.company = '"+qcId+"'");
		inspectorsHql.append("order by addtime desc");
		List<Account> inspectorsData=accountDao.findPage(inspectorsHql.toString(), rows, (page - 1) * rows);
		return inspectorsData;
	}
	
	@Override
	public int findInspectorsData( int qcId) {
		StringBuffer inspectorsHql = new StringBuffer();
		inspectorsHql.append("from Account as inspectors where 1=1");
		inspectorsHql.append("and inspectors.company = '"+qcId+"'");
		List<Account> inspectorsData=accountDao.findByHql(inspectorsHql.toString());
		int count = inspectorsData.size();
		return count;
	}

	@Override
	public List<AccountVO> getVo(List<Account> accounts) {
		List<AccountVO> accountListVo = new ArrayList<AccountVO>();
		AccountVO accountVo = new AccountVO();
		for (Account account : accounts) {
			accountVo = new AccountVO();
			accountVo.setAccount(account.getAccount());
			accountVo.setAccountId(account.getAccountId());
			accountVo.setAccountTypeName(account.getAccountTypeName());
			accountVo.setAddress(account.getAddress());
			accountVo.setAddTime(account.getAddTime());
			accountVo.setAttestStatusName(account.getAttestStatusName());
			accountVo.setBirthday(account.getBirthday());
			accountVo.setCnasFlag(account.getCnasFlag());
			accountVo.setCompName(account.getCompName());
			accountVo.setCompNatureName(account.getCompNatureName());
			accountVo.setEmail(account.getEmail());
			accountVo.setFax(account.getFax());
			accountVo.setHeadImgURL(account.getHeadImgURL());
			accountVo.setImg1(account.getImg1());
			accountVo.setImg2(account.getImg2());
			accountVo.setJinyongFlag(account.getJinyongFlag());
			accountVo.setLinkMan(account.getLinkMan());
			accountVo.setNickName(account.getNickName());
			accountVo.setPassword(account.getPassword());
			accountVo.setPhone(account.getPhone());
			accountVo.setSex(account.getSex());
			accountVo.setCompNature(account.getCompNature());
			accountVo.setAttestStatus(account.getAttestStatus());
			accountVo.setAccountType(account.getAccountType());
//			检验人员 搜索结果用了 CompNature暂存
			accountVo.setInspectors(account.getCompNature());
			
			accountListVo.add(accountVo);
		}
		return accountListVo;
	}
	
	
}
